<script lang="ts" setup>
import { get, post, Message, loadFile, message } from '@/utils'
type Emits = {
  success: [img: string]
  'update:list': [list: string[]]
  remove: [index: number]
  fail: []
  file: any
  'update:value': [string]
  'update:val': [string]
  'update:data': [any]
}
const props = withDefaults(
  defineProps<{
    separator?: string //切割标识
    list?: any[] | string //文件列表|需要根据标识切割的字符串
    preview?: boolean //开启图片预览
    accept?: string //上传文件类型
    disabled?: boolean //禁用
    multiple?: boolean //多文件上传
    tip?: string
    value?: string
    limit?: number //上传数量
    showRemoveBtn?: boolean //显示删除按钮
    showBtn?: boolean //是否显示上传按钮
    listType?: 'text' | 'picture' | 'picture-card' //图片列表类型
    api?: string
    fileName?: string
    notUpload?: boolean
    showFileList?: boolean
    formDataFileKey?: string
    formData?: any //自定义接口接收的formdata
  }>(),
  {
    notUpload: false,
    preview: true,
    disabled: false,
    multiple: false,
    accept: '*',
    limit: 0,
    showRemoveBtn: true,
    showBtn: true,
    showFileList: true,
    separator: ',',
    listType: 'picture-card',
    formDataFileKey: 'file',
    api: '/server-resource/oss/endpoint/upload/file',
  }
)

const valStr = ref('')
const emit = defineEmits<Emits>()
const fileList = ref<any[]>([])
/**等待上传的图片 */
const waitUploadList = ref<any[]>([])
/**上传图片 */
const customRequest = option => {
  const { onProgress, onSuccess, fileItem, name } = option
  // emit('update:val', fileItem.file)
  //   waitUploadList.value.push(fileItem.file)
  onProgress(100)
  onSuccess()
  console.log(props.formData)
  // getBase64(fileItem.file)
  if (props.formData) {
    console.log('🚀 ~ customRequest ~ props:', props)
    onUpload(fileItem.file)
  }
  return {
    abort() {},
  }
}
const getBase64 = file => {
  return new Promise(function (resolve, reject) {
    const reader = new FileReader()
    let imgResult: any = ''
    reader.readAsDataURL(file)
    reader.onload = function () {
      imgResult = reader.result
    }
    reader.onerror = function (error) {
      reject(error)
    }
    reader.onloadend = function () {
      resolve(imgResult)
    }
  })
}
const onUpload = item => {
  console.log('🚀 ~ onUpload ~ item:', item)
  return new Promise(async (resolve, reject) => {
    const formData = new FormData()
    Object.keys(props.formData).forEach(key => {
      formData.append(key, props.formData[key])
    })
    formData.append(props.formDataFileKey, item)
    emit('update:value', valStr.value)
    const base64 = (await getBase64(item)) as any
    /**截取base64声明前缀 */
    emit('update:val', base64.split(',')[1])
  })
}
/**删除 */
const onRemove = (fileItem): any => {
  return new Promise((resolve, reject) => {
    const _index = fileList.value.findIndex(f => f.url == fileItem.url)
    console.log(_index)
    if (_index != -1) {
      emit('remove', _index)
      // fileList.value.splice(_index, 1);
      const list = valStr.value.split(',').filter(Boolean)
      list.splice(_index, 1)
      valStr.value = list.join(',')
      emit('update:value', valStr.value)
      resolve(true)
    } else reject(false)
  })
}
const initImg = img => {
  fileList.value = []
  if (img && typeof img === 'string') {
    img
      .split(props.separator)
      .filter(Boolean)
      .forEach((item, i) => {
        fileList.value.push({
          url: item,
          name: (props.fileName ?? '') + '文件' + (i + 1),
        })
      })
    valStr.value = props.list as string
  } else {
    if (!img?.length) return
    ;(img as any[]).map((v, i) => {
      fileList.value.push({
        url: v,
        name: (props.fileName ?? '') + (i + 1),
      })
    })
  }
}
/**监听重置fileList */
watch(
  () => props.list,
  newVal => {
    initImg(newVal)
  }
)
onMounted(() => {
  initImg(props.list)
})
defineExpose({
  onUpload(cb) {
    const requstList: Promise<any>[] = []

    waitUploadList.value.forEach(item => {
      requstList.push(onUpload(item))
    })
    Promise.all(requstList).then(() => {
      emit('update:value', valStr.value)
      emit('update:data', '')
      cb()
    })
  },
})
</script>
<template>
  <a-upload
    :list-type="props.listType"
    action="/"
    :limit="props.limit"
    v-model:file-list="fileList"
    :image-preview="props.preview"
    :disabled="props.disabled"
    :multiple="props.multiple"
    :showFileList="props.showFileList"
    :show-remove-button="props.showRemoveBtn"
    :tip="props.tip"
    :show-upload-button="props.showBtn"
    :accept="props.accept"
    :custom-request="customRequest"
    @before-remove="fileItem => onRemove(fileItem)"
  />
</template>
<style lang="less" scoped></style>
